package com.jy.wms.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.*;
import com.jy.wms.dao.*;
import com.jy.wms.pojo.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName: WmsArtificialReplenishmentService.java
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author LH
 * @Date Mon Nov 27 17:18:33 GMT+08:00 2017
 */

@Service
public class WmsArtificialReplenishmentService extends BaseService<WmsArtificialReplenishmentMapper, WmsArtificialReplenishment> {
    @Autowired
    WmsOrderRepairService wmsOrderRepairService;
    @Autowired
    WmsOrderRepairMapper wmsOrderRepairMapper;
    @Autowired
    WmsArtificialReplenishmentRecordMapper wmsArtificialReplenishmentRecordMapper;
    @Autowired
    WmsArtificialReplenishmentDetailedMapper wmsArtificialReplenishmentDetailedMapper;
    @Autowired
    WmsArtificialReplenishmentStockMapper wmsArtificialReplenishmentStockMapper;
    @Autowired
    WmsOwnerMapper wmsOwnerMapper;
    @Autowired
    WmsStockMapper wmsStockMapper;
    @Autowired
    WmsGoodsMapper wmsGoodsMapper;
    @Autowired
    WmsPdaReplenishmentMapper wmsPdaReplenishmentMapper;
    @Autowired
    WmsPdaMsgMapper wmsPdaMsgMapper;
    /**
     * 分页查询
     *
     * @param entity 实体
     * @return Page<WmsArtificialReplenishment>
     */
    public Page<WmsArtificialReplenishment> baseSelectPage(WmsArtificialReplenishment entity, String ckid) {
        PageHelper.startPage(entity.getPage(), entity.getRows());
        return (Page<WmsArtificialReplenishment>) dao.baseSelectPage(entity, ckid);
    }


    /**
     * 新增补货单明细时，首先获取相应的库存信息
     *
     * @return
     */
    public Page<WmsArtificialReplenishment> getGoods(String hpmc, String hpbh, String ckid, String hzid, int page, int rows) throws ServiceException {
        try {
            PageHelper.startPage(page, rows);
            return (Page<WmsArtificialReplenishment>) dao.getGoods(hpmc, hpbh, ckid, hzid);
        } catch (Exception e) {
            throw new ServiceException("新增补货单明细，获取库存信息", e);
        }
    }

    /**
     * 获取补货编号
     *
     * @return
     */
    public String getBhbh() {
        String bhbh = wmsOrderRepairService.getBhbh("2");//获取补货编号
        return bhbh;
    }

    /**
     * 插入一条记录（匹配有值的字段）
     *
     * @param entity 实体对象
     * @return int
     */
    @Transactional
    public Integer baseInsertSelective(WmsArtificialReplenishment entity, UserInfo userInfo, String ckid, String hzid) throws SucessException, ServiceException {
        WmsArtificialReplenishmentRecord wmsArtificialReplenishmentRecord = new WmsArtificialReplenishmentRecord();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = df.format(new Date());// new Date()为获取当前系统时间
        logger.info("增加人工补货开始时间："+df.format(new Date()));

        //明细集合
        List<WmsArtificialReplenishmentDetailed> wardList = entity.getWardList();
        if (wardList.size() > 0) {
            //String bhbh = wmsOrderRepairService.getBhbh("2");//获取补货编号
            // entity.setBh(bhbh);
            entity.setId(UUIDUtils.uuid());
            entity.setCkid(ckid);
            entity.setHzid(hzid);
            //增加人工补货主表
            Integer a = dao.baseInsertSelective(entity);
            //增加人工补货记录表
            wmsArtificialReplenishmentRecord.setId(UUIDUtils.uuid());
            wmsArtificialReplenishmentRecord.setBhid(entity.getId());
            wmsArtificialReplenishmentRecord.setCjr(userInfo.getUser().getName());
            wmsArtificialReplenishmentRecord.setXgr(userInfo.getUser().getName());
            wmsArtificialReplenishmentRecord.setCjsj(date);
            wmsArtificialReplenishmentRecord.setXgsj(date);
            wmsArtificialReplenishmentRecord.setCkid(ckid);
            wmsArtificialReplenishmentRecord.setHzid(hzid);
            Integer b = wmsArtificialReplenishmentRecordMapper.baseInsertSelective(wmsArtificialReplenishmentRecord);
            for (WmsArtificialReplenishmentDetailed ward : wardList) {
                ward.setId(UUIDUtils.uuid());
                ward.setBhid(entity.getId());
                ward.setCkid(ckid);
                ward.setHzid(hzid);
            }
            //增加人工补明细表
            Integer c = wmsArtificialReplenishmentDetailedMapper.baseInsertSelective(wardList);
            logger.info("增加人工补货结束时间："+df.format(new Date()));
            if (a > 0 && b > 0 && c > 0) {
                throw new SucessException("新增补货单成功");
            } else {
                throw new ServiceException("新增补货单失败");
            }
        } else {
            throw new ServiceException("补货单明细不可为空");
        }
    }


    /**
     * 删除（根据ID 批量删除）
     *
     * @param idList 主键ID列表
     * @return int
     */
    @Transactional
    public Integer baseDeleteBathPrimaryKeys(List<String> idList, UserInfo userInfo) throws SucessException, ServiceException {
        List<WmsArtificialReplenishment> list = dao.selectBatchIds(idList);
        List<String> list2 = new ArrayList<String>();
        for (WmsArtificialReplenishment war : list) {
            //未审核
            if (war.getZt().compareTo(BigDecimal.ZERO) == 0) {
                list2.add(war.getId());
            }
        }
        if (list2.size() > 0) {
            Integer a = dao.baseDeleteBathPrimaryKeys(list2, "3");//修改补货单主表的状态，改为作废
            //修改补货单记录表的删除人及删除时间
            WmsArtificialReplenishmentRecord wmsArtificialReplenishmentRecord = new WmsArtificialReplenishmentRecord();
            wmsArtificialReplenishmentRecord.setDeleter(userInfo.getUser().getName());
            Integer b = wmsArtificialReplenishmentRecordMapper.baseUpdateByPrimaryKeySelective(idList, wmsArtificialReplenishmentRecord);
            if (a > 0 & b > 0) {
                throw new SucessException("选中" + idList.size() + "条记录，删除成功" + a + "条记录");
            } else {
                throw new ServiceException("补货单删除失败");
            }
        } else {
            throw new ServiceException("选中的记录不包含初始状态的，删除失败");
        }
    }

    /**
     * 修改 （匹配有值的字段）
     *
     * @param entity 主键ID列表
     * @return int
     */
    public Integer baseUpdateByPrimaryKey(WmsArtificialReplenishment entity, UserInfo userInfo) throws ServiceException, SucessException {
        WmsArtificialReplenishmentRecord wmsArtificialReplenishmentRecord = new WmsArtificialReplenishmentRecord();
        WmsArtificialReplenishment wmsArtificialReplenishment = dao.baseSelectByPrimaryKey(entity.getId());//通过id查询对象

        if (wmsArtificialReplenishment.getZt().compareTo(BigDecimal.ZERO) != 0) {
            throw new ServiceException("补货单不是“初始”状态，不可以编辑");
        } else {
            //修改补货单
            Integer b = dao.baseUpdateByPrimaryKeySelective(entity);
            wmsArtificialReplenishmentRecord.setBhid(entity.getId());
            wmsArtificialReplenishmentRecord.setXgr(userInfo.getUser().getName());
            //修改补货单记录表
            Integer c = wmsArtificialReplenishmentRecordMapper.baseUpdateXgr(wmsArtificialReplenishmentRecord);
            if (b > 0 & c > 0) {
                throw new SucessException("补货单编辑成功");
            } else {
                throw new ServiceException("补货单编辑失败");
            }
        }

    }


    @BaseServiceDescribe(moduleName = "补货单", btnName = "查询明细集合")
    public JSONArray getDetailList(List<String> idList) throws ServiceException {
        try {
            //发运订单明细
            List<WmsArtificialReplenishmentDetailed> list = dao.getDetailList(idList);
            return JSONArray.fromObject(list);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询发运订单及明细", e);
        }
    }

    @BaseServiceDescribe(moduleName = "补货单", btnName = "生成补货单")
    @Transactional
    public JSONArray generateReplenishment(List<String> idList, String hzid, String qrr) throws ServiceException, SucessException {
        WmsArtificialReplenishmentRecord wmsArtificialReplenishmentRecord = new WmsArtificialReplenishmentRecord();

        wmsArtificialReplenishmentRecord.setScr(qrr);
        WmsArtificialReplenishmentStock wmsArtificialReplenishmentStock = new WmsArtificialReplenishmentStock();
        WmsOwner wmsOwner = wmsOwnerMapper.selectById(hzid);//获取货主的信息
        //根据补货单id获取补货明细集合
        List<WmsArtificialReplenishmentDetailed> list = dao.getDetailLists(idList);
        //根据周转规则中间表获取排序字段
        List<String> gzList = wmsOrderRepairMapper.getGzzd(hzid);

        if (("1").equals(wmsOwner.getBhzdqr())) {//补货自动确认(生成补货单和确认补货 同时完成)
            boolean aa = true;
            //和补货上限比较（该货品原库存的数量加上补货数量与补货上限比较）
            aa = comparBhsx(list, aa);
            if (aa == true) {
                updateQrr(idList, qrr);//修改确认人，确认时间和状态
                Integer a = 0;
                Integer c = 0;
                Integer count2 = 0;
                Integer count = 0;
                //修改记录表的生成人及生成时间
                Integer count1 = wmsArtificialReplenishmentRecordMapper.baseUpdateByPrimaryKeySelective(idList, wmsArtificialReplenishmentRecord);
                //修改主表的状态更改为（已生成）
                Integer b = dao.baseDeleteBathPrimaryKeys(idList, "2");
                for (WmsArtificialReplenishmentDetailed ward : list) {
                    Double bhsl = ward.getSl().doubleValue();
                    //拣货位对应的该货品的库存
                    WmsStock wmsStock = wmsOrderRepairMapper.getWmsStock(ward.getKwid(), ward.getHpid());
                    List<WmsStock> KyStockList = wmsOrderRepairMapper.getKyStock(gzList, ward.getHpid());//获取可用库存
                    if (KyStockList.size() > 0) {
                        for (WmsStock wStock : KyStockList) {
                            //可用库存
                            Double kykc = Double.parseDouble(wStock.getSl()) - Double.parseDouble(wStock.getDxjsl()) - Double.parseDouble(wStock.getDzysl()) - Double.parseDouble(wStock.getDjsl()) - Double.parseDouble(wStock.getPssl()) - Double.parseDouble(wStock.getBhsl());
                            if (kykc > 0) {
                                if (bhsl > kykc) {
                                    wmsArtificialReplenishmentStock.setSl(new BigDecimal(kykc));
                                    bhsl = bhsl - kykc;
                                } else if (bhsl <= kykc && bhsl > 0) {
                                    wmsArtificialReplenishmentStock.setSl(new BigDecimal(bhsl));
                                    bhsl = bhsl - kykc;
                                } else if (bhsl <= 0) {
                                    break;
                                }
                                //增加人工驱动补货库存记录
                                wmsArtificialReplenishmentStock.setId(UUIDUtils.uuid());
                                wmsArtificialReplenishmentStock.setBhmxid(ward.getId());
                                wmsArtificialReplenishmentStock.setBhhpkcid(wStock.getId());//补货库存id
                                wmsArtificialReplenishmentStock.setXhpkcid(wmsStock.getId());//确认库存id
                                a = wmsArtificialReplenishmentStockMapper.baseInsertSelective(wmsArtificialReplenishmentStock);
                                a++;

                                Map<String, Integer> map = updateJhkc(ward, wmsStock, wStock);
                                count = map.get("count");//生成拣货库存
                                count2 = map.get("count2");//修改拣货库存
                                // 新生成的待拣货数量、待补货数量、破损数量、冻结数量全部为零。其他字段与原库存相同。

                            }
                        }
                    }
                }
                if (a > 0 && b > 0) {
                    throw new SucessException("补货单生成成功");
                } else {
                    throw new ServiceException("未生成补货单");
                }
                //throw new SucessException("确认成功" + count2 + "条记录，生成拣货位库存" + count + "条");
            } else {
                throw new ServiceException("补货数量已超过补货上限，新增和确认失败");
            }
        } else {
            Integer a = 0;
            //修改记录表的生成人及生成时间
            Integer count1 = wmsArtificialReplenishmentRecordMapper.baseUpdateByPrimaryKeySelective(idList, wmsArtificialReplenishmentRecord);
            //修改主表的状态更改为（已生成）
            Integer b = dao.baseDeleteBathPrimaryKeys(idList, "1");
            for (WmsArtificialReplenishmentDetailed ward : list) {
                Double bhsl = ward.getSl().doubleValue();
                //获取可用库存
                List<WmsStock> KyStockList = wmsOrderRepairMapper.getKyStock(gzList, ward.getHpid());
                if (KyStockList.size() > 0) {
                    for (WmsStock wStock : KyStockList) {

                        //可用库存
                        Double kykc = Double.parseDouble(wStock.getSl()) - Double.parseDouble(wStock.getDxjsl()) - Double.parseDouble(wStock.getDzysl()) - Double.parseDouble(wStock.getDjsl()) - Double.parseDouble(wStock.getPssl()) - Double.parseDouble(wStock.getBhsl());
                        if (kykc > 0) {
                            if (bhsl > kykc) {
                                // 找到库存后锁定库存ID，在原有的待补货数量增加此次找寻的库存数量。
                                Integer count = wmsOrderRepairMapper.updateBhsl(wStock.getId(), String.valueOf((new BigDecimal(wStock.getBhsl()).add( new BigDecimal(kykc))).intValue()));
                                //wmsOrderRepairDetailed.setBhsl(new BigDecimal(kykc));//补货数量
                                wmsArtificialReplenishmentStock.setSl(new BigDecimal(kykc));
                                bhsl = bhsl - kykc;
                            } else if (bhsl <= kykc && bhsl > 0) {
                                Integer count = wmsOrderRepairMapper.updateBhsl(wStock.getId(), String.valueOf( (new BigDecimal(wStock.getBhsl()).add( new BigDecimal(bhsl))).intValue() ));
                                wmsArtificialReplenishmentStock.setSl(new BigDecimal(bhsl));
                                bhsl = bhsl - kykc;
                            } else if (bhsl <= 0) {
                                break;
                            }
                            //增加人工驱动补货库存记录
                            wmsArtificialReplenishmentStock.setId(UUIDUtils.uuid());
                            wmsArtificialReplenishmentStock.setBhmxid(ward.getId());
                            wmsArtificialReplenishmentStock.setBhhpkcid(wStock.getId());
                            a = a+wmsArtificialReplenishmentStockMapper.baseInsertSelective(wmsArtificialReplenishmentStock);

                        }
                    }
                }

            }
            if (a > 0) {
                throw new SucessException("补货单生成成功");
            } else {
                throw new ServiceException("未生成补货单");
            }
        }


    }

    /**
     *
     * @param ward
     * @param wmsStock 拣货位库存
     * @param wStock  存储区库存
     * @return
     */
    private Map<String, Integer> updateJhkc(WmsArtificialReplenishmentDetailed ward, WmsStock wmsStock, WmsStock wStock) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        Integer count2 = 0;
        Integer count = 0;
        if (wmsStock != null) {
            //拣货位库存
            wmsStock.setSl(String.valueOf((ward.getBhsl().add(new BigDecimal(wmsStock.getSl()))).intValue()));
            count2 =count2+ wmsStockMapper.baseUpdateByPrimaryKeySelective(wmsStock);//修改拣货位库存，增加补货的数量
            wmsArtificialReplenishmentStockMapper.updateXhpkcid(wmsStock.getId(),ward.getId());//修改确认库存id
        } else {
            wStock.setKwid(ward.getKwid());
            //将补货数量生成新的拣货位库存。新库存与原库存只有库位、数量、创建时间的不同，
            // 新生成的待拣货数量、待补货数量、破损数量、冻结数量全部为零。其他字段与原库存相同。
            count = count+generateStock(ward, wStock);

        }
        map.put("count2", count2);
        map.put("count", count);
        return map;
    }

    /**
     * 确认时修改确认人及时间，状态
     *
     * @param list2 需要确认的主表的id集合
     * @param qrry 确认人员
     * @return
     */

    public boolean updateQrr(List<String> list2, String qrry) {
        WmsArtificialReplenishmentRecord wmsArtificialReplenishmentRecord = new WmsArtificialReplenishmentRecord();
        wmsArtificialReplenishmentRecord.setQrr(qrry);
        //修改记录表的确认人及确认时间
        Integer a = wmsArtificialReplenishmentRecordMapper.baseUpdateByPrimaryKeySelective(list2, wmsArtificialReplenishmentRecord);
        //修改主表的状态更改为（已确认）
        Integer b = dao.baseDeleteBathPrimaryKeys(list2, "2");
        return a > 0 && b > 0;
    }


    @BaseServiceDescribe(moduleName = "补货单", btnName = "确认补货单")
    @Transactional
    public Integer confirmOrders(String bhid, String qrry) throws SucessException, ServiceException {
        //(1)	只能确认  补货单状态为“已生成”的单子 并且 补货任务生成状态 为初始的单子
        WmsArtificialReplenishmentRecord wmsArtificialReplenishmentRecord = new WmsArtificialReplenishmentRecord();
        //获取选中id的集合
        WmsArtificialReplenishment wmsArtificialReplenishment = dao.baseSelectByPrimaryKey(bhid);
        //已生成
        if ("1".equals(String.valueOf(wmsArtificialReplenishment.getZt()))&& "0".equals(String.valueOf(wmsArtificialReplenishment.getSczt()))) {
            //查找单独一个补货单下的明细集合
            List<WmsArtificialReplenishmentDetailed> detailedList = wmsArtificialReplenishmentStockMapper.selectBhid(bhid);
            boolean a = true;
            //和补货上限比较（该货品原库存的数量加上补货数量与补货上限比较）
            a = comparBhsx(detailedList, a);
            Integer count = 0;
            Integer count1 = 0;
            if (a == true) {
                List<String> list = new ArrayList<String>();
                list.add(bhid);
                //确认时修改确认人及时间，状态
                boolean flag = updateQrr(list, qrry);
                for (WmsArtificialReplenishmentDetailed word : detailedList) {
                    //确认后根据订单驱动补货明细表中的库存ID，将库存ID对应的库存扣减待补货数量，扣减数量。
                    WmsStock ws = wmsStockMapper.selectById(word.getBhhpkcid());//通过库存id获取库存对象
                    BigDecimal bhsl = new BigDecimal(ws.getBhsl()).subtract(word.getBhsl());
                    BigDecimal sl = new BigDecimal(ws.getSl()).subtract(word.getBhsl());
                    ws.setBhsl(String.valueOf(bhsl.intValue()));//原待补货数量减去补货数量
                    ws.setSl(String.valueOf(sl.intValue()));
                    Integer c = wmsStockMapper.updateById(ws);//将库存ID对应的库存扣减待补货数量，扣减数量。

                    //获取拣货位的库存
                    WmsStock wmsStock = wmsOrderRepairMapper.getWmsStock(word.getKwid(), word.getHpid());
                    //如果该拣货位对应货品的库存为空，那么新建一条拣货位的库存，否则修改原拣货位的库存


                    Map<String, Integer> map = updateJhkc(word, wmsStock, ws);
                    count = count+map.get("count");
                    count1 = count1+map.get("count2");
                }
                throw new SucessException("确认成功" + count1 + "条记录，生成拣货位库存" + count + "条");

                //查看每条明细的 拣货位原有库存加上此次补货数量是否大于补货上限
               /* for (WmsArtificialReplenishmentStock word : detailedList) {
                    //补货上限
                    BigDecimal bhsx= new BigDecimal( wmsGoodsMapper.baseSelectByPrimaryKey(word.getHpid()).getBhsx());
                    //获取拣货位的库存
                    WmsStock wmsStock = wmsOrderRepairMapper.getWmsStock(word.getKwid(), word.getHpid());

                    WmsStock ws = wmsStockMapper.selectById(word.getBhhpkcid());//通过库存id获取库存对象
                    BigDecimal bhsl = new BigDecimal(ws.getBhsl()).subtract(word.getSl());
                    BigDecimal sl = new BigDecimal(ws.getSl()).subtract(word.getSl());
                    ws.setBhsl(String.valueOf(bhsl));//原待补货数量减去补货数量
                    ws.setSl(String.valueOf(sl));
                    Integer c = wmsStockMapper.updateById(ws);//将库存ID对应的库存扣减待补货数量，扣减数量。
                    //如果该拣货位对应货品的库存为空，那么新建一条拣货位的库存，否则修改原拣货位的库存
                    if(wmsStock!=null){
                        //如果拣货位原有库存加上此次补货数量大于补货上限，那么这条明细对应的相应的补货单都不可以进行确认

                        ws.setSl(String .valueOf(word.getSl().add(new BigDecimal(ws.getBhsl()))));
                         wmsStockMapper.baseUpdateByPrimaryKeySelective(ws);//修改拣货位库存，增加补货的数量

                    }else {
                        //将补货数量生成新的库存。新库存与原库存只有库位、数量、创建时间的不同，
                        // 新生成的待拣货数量、待补货数量、破损数量、冻结数量全部为零。其他字段与原库存相同。
                        generateStock(word, ws);
                    }
                }*/

            } else {
                throw new ServiceException("补货数量已超过补货上限，确认失败");
            }
        } else {
            throw new ServiceException("只能确认状态为\'已生成\'且补货任务生成状态为\'初始\'的记录");
        }
    }

    //和补货上限比较（该货品原库存的数量加上补货数量与补货上限比较）
    private boolean comparBhsx(List<WmsArtificialReplenishmentDetailed> detailedList, boolean a) {
        for (int i = 0; i < detailedList.size(); i++) {
            int flags;
            //补货上限
            BigDecimal bhsx = new BigDecimal(wmsGoodsMapper.baseSelectByPrimaryKey(detailedList.get(i).getHpid()).getBhsx());
            //获取拣货位的库存
            WmsStock wmsStock = wmsOrderRepairMapper.getWmsStock(detailedList.get(i).getKwid(), detailedList.get(i).getHpid());
            if(wmsStock!=null){
                 flags = detailedList.get(i).getSl().add(new BigDecimal(wmsStock.getSl())).compareTo(bhsx);//比较
            }else{
                 flags = detailedList.get(i).getSl().add(new BigDecimal(0)).compareTo(bhsx);//比较
            }

            if (flags != -1) { //不小于
                a = false;
            }
        }
        return a;
    }


    /**
     * 新生成的待拣货数量、待补货数量、破损数量、冻结数量全部为零。其他字段与原库存相同。
     *
     * @param word
     * @return
     */
    public Integer generateStock(WmsArtificialReplenishmentDetailed word, WmsStock ws) {
        // WmsStock ws = wmsStockMapper.selectById(word.getBhhpkcid());//通过库存id获取库存对象
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        ws.setCjsj(df.format(new Date()));
        ws.setSl(String.valueOf(word.getSl().intValue()));//数量为补货数量
        ws.setDxjsl("0");
        ws.setDzysl("0");
        ws.setDjsl("0");
        ws.setPssl("0");
        ws.setId(UUIDUtils.uuid());
        Integer d = wmsStockMapper.baseInsertSelective(ws);//生成新的库存d
        wmsArtificialReplenishmentStockMapper.updateXhpkcid(ws.getId(),word.getId());//修改确认库存id
        return d;
    }

    /**
     * 取消原库存（当生成的补货单在确认的时候原库存的数量加上补货数量大于补货上限时无法进行确认了，这时候就需要把生成的补货单作废掉，就是减去库存里锁定的数据）
     *
     * @param bhid 补货单id
     * @return
     */
    @Transactional
    public void cancelBhd(String bhid) throws ServiceException, SucessException {
        List<String> list = new ArrayList<String>();
        list.add(bhid);
        int count = 0;

        WmsArtificialReplenishment war = dao.selectById(bhid);
        //如果已下发补货任务那么不能进行取消补货操作
        if (war.getSczt().equals("0")) {//未下发


            //查找单独一个补货单下的明细集合
            List<WmsArtificialReplenishmentDetailed> detailedList = wmsArtificialReplenishmentStockMapper.selectBhid(bhid);
            Integer a = dao.baseDeleteBathPrimaryKeys(list, "0");//修改补货单主表的状态，改为初始

            for (WmsArtificialReplenishmentDetailed word : detailedList) {
                //确认后根据订单驱动补货明细表中的库存ID，将库存ID对应的库存扣减待补货数量，扣减数量。
                //通过库存id获取库存对象
                WmsStock ws = wmsStockMapper.selectById(word.getBhhpkcid());

                // if(new BigDecimal(ws.getBhsl()).compareTo(word.getSl())!=-1){//如果原库存的补货数量小于此明细的补货数量，那么给出提示，不允许出现负数
                // 找到库存后锁定库存ID，在原有的待补货数量减掉明细的补货数量。
                int bhsl = (new BigDecimal(ws.getBhsl()).subtract(word.getBhsl())).intValue();
                count = count + wmsOrderRepairMapper.updateBhsl(ws.getId(), String.valueOf(bhsl));
                //删除人工补货库存表的记录
                Integer b = wmsArtificialReplenishmentStockMapper.delete(new EntityWrapper<WmsArtificialReplenishmentStock>().eq("bhmxid", word.getId()));

           /* }else {
            }*/

            }
        } else {
            throw new ServiceException("已下发补货任务，无法取消补货");
        }
        if (count > 0) {
            throw new SucessException("取消补货单成功");
        } else {
            throw new ServiceException("取消补货单失败");
        }
    }


    @Transactional
    @BaseServiceDescribe(moduleName = "补货单", btnName = "下发补货任务")
    public void  addBhRw(String id,String hzid,String userId,String userName,String ckid) throws ServiceException, SucessException {
        //补货单
        WmsArtificialReplenishment wmsArtificialReplenishment = dao.selectById(id);
        //补货单明细集合
        List<WmsArtificialReplenishmentDetailed> list=wmsArtificialReplenishmentStockMapper.getList(id);
        //货主
        WmsOwner wmsOwner= wmsOwnerMapper.selectById(hzid);
        Integer num=0;
        //补货单状态为“已生成”的补货单可以点击“下发补货任务”
        if (wmsArtificialReplenishment.getZt().toString().equals("1")) {// "已生成"
            for (WmsArtificialReplenishmentDetailed wmsArtificialReplenishmentDetailed : list) {
                //获取生产日期和货品批次
                WmsStock wmsStock = dao.getScrqByMxid(wmsArtificialReplenishmentDetailed.getBhhpkcid());
                //把数据写入pda补货任务表
                WmsPdaReplenishment wmsPdaReplenishment = new WmsPdaReplenishment();
                wmsPdaReplenishment.setId(UUIDUtils.uuid());
                wmsPdaReplenishment.setBhdh(wmsArtificialReplenishment.getBh());//补货单号
                wmsPdaReplenishment.setBhlx("1");//补货类型 0：订单驱动 1：人工驱动
                wmsPdaReplenishment.setBhckwid(wmsArtificialReplenishmentDetailed.getBhckwid());//补货出库位ID
                wmsPdaReplenishment.setBhckw(wmsArtificialReplenishmentDetailed.getBhckw());//补货出库位
                wmsPdaReplenishment.setBhrkwid(wmsArtificialReplenishmentDetailed.getBhrkwid());//补货入库位ID
                wmsPdaReplenishment.setBhrkw(wmsArtificialReplenishmentDetailed.getBhrkw());//补货入库位
                wmsPdaReplenishment.setHpbh(wmsArtificialReplenishmentDetailed.getHpbh());
                wmsPdaReplenishment.setHpmc(wmsArtificialReplenishmentDetailed.getHpmc());
                wmsPdaReplenishment.setHpid(wmsArtificialReplenishmentDetailed.getHpid());
                wmsPdaReplenishment.setBhsl(wmsArtificialReplenishmentDetailed.getSl());
                wmsPdaReplenishment.setBhryid(userId);//补货人员id
                wmsPdaReplenishment.setBhrymc(userName);//补货人员名称
                wmsPdaReplenishment.setBhdid(wmsArtificialReplenishment.getId());
                wmsPdaReplenishment.setKcid(wmsArtificialReplenishmentDetailed.getBhhpkcid());
                //如果货主的扫描货品码和扫描lpn 码为“是”，给lpn码和货品码赋值
                if(wmsOwner.getCmhpm().equals("1")&& wmsOwner.getSmLpn().equals("1")){
                    wmsPdaReplenishment.setLpn(wmsArtificialReplenishmentDetailed.getLpn());
                    wmsPdaReplenishment.setHptm(wmsArtificialReplenishmentDetailed.getHpbh());//给货品码赋货品编码 的值
                }
                wmsPdaReplenishment.setXdw(wmsArtificialReplenishmentDetailed.getXdw());//箱单位描述
                wmsPdaReplenishment.setZdw(wmsArtificialReplenishmentDetailed.getZdw());//主单位描述
                wmsPdaReplenishment.setHsl(new BigDecimal(wmsArtificialReplenishmentDetailed.getHsl()));//换算量
                wmsPdaReplenishment.setHppc(wmsArtificialReplenishmentDetailed.getHppc());
                wmsPdaReplenishment.setScrq(wmsArtificialReplenishmentDetailed.getScrq());
                wmsPdaReplenishment.setGys(wmsArtificialReplenishmentDetailed.getGys());
                wmsPdaReplenishment.setCkid(ckid);
                wmsPdaReplenishment.setHzid(hzid);
                wmsPdaReplenishment.setBhmxid(wmsArtificialReplenishmentDetailed.getId());
                wmsPdaReplenishment.setHppc(wmsStock.getHppc());
                wmsPdaReplenishment.setScrq(wmsStock.getScrq());
                wmsPdaReplenishment.setSfkjdps(wmsOwner.getDjdps());
                wmsPdaReplenishmentMapper.baseInsertSelective(wmsPdaReplenishment);

                //pda消息表
                WmsPdaMsg wmsPdaMsg=new WmsPdaMsg();
                wmsPdaMsg.setRyid(userId);
                wmsPdaMsg.setBt(wmsArtificialReplenishment.getBh());
                wmsPdaMsg.setXx(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+" 人工补货下发补货任务");
                wmsPdaMsg.setZt("0");
                wmsPdaMsgMapper.baseInsertSelective(wmsPdaMsg);
                num++;

                //修改补货单的生成状态 为“已生成”
                int a = dao.updateSczt(1, id);
            }
            if(num>0){
                throw new SucessException("下发补货任务成功");
            }else{
                throw new ServiceException("下发补货任务失败");
            }
        } else {
            throw new ServiceException("只能下发状态为 已生成 的补货单");
        }
    }






    /**
     * 导出驱动补货订单
     *
     * @param idList
     * @return
     */
    public List<WmsArtificialReplenishmentDetailed> getOutPutList(List<String> idList, Map map) {
        return dao.getOutPutList(idList);
    }


    /**
     * 打印补货单
     * @param idList 选中的id
     * @return
     */
    public JSONObject print(List<String> idList) throws ServiceException {


        try {
            WmsArtificialReplenishment wmsArtificialReplenishment= dao.selectByBhid(idList.get(0));
            List<WmsArtificialReplenishmentDetailed> list= dao.getOutPutList(idList);
            wmsArtificialReplenishment.setWardList(list);
            //dao.getOutPutList(idList);
            return JSONObject.fromObject(wmsArtificialReplenishment);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("打印补货单", e);
        }
    }
    /**
     * 插入一条记录
     *
     * @param entity 实体对象
     * @return int
     */
    public Integer baseInsert(WmsArtificialReplenishment entity) {
        return dao.baseInsert(entity);
    }

    /**
     * 删除（根据主键ID删除）
     *
     * @param id 主键
     * @return int
     */
    public Integer baseDeleteByPrimaryKey(String id) {
        return dao.baseDeleteByPrimaryKey(id);
    }

    /**
     * 查询（根据主键ID查询）
     *
     * @param id 主键ID
     * @return WmsArtificialReplenishment
     */
    public WmsArtificialReplenishment baseSelectByPrimaryKey(String id) {
        return dao.baseSelectByPrimaryKey(id);
    }

    /**
     * 查询（根据ID 批量查询）
     *
     * @param idList 主键ID列表
     * @return list
     */
    public Integer baseSelectBathPrimaryKeys(List<WmsArtificialReplenishment> idList) {
        return dao.baseSelectBathPrimaryKeys(idList);
    }


}
